package com.rabbit.videoplayer

import android.animation.Animator
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.media.AudioManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.DrawableRes
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_DEFAULT
import androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.source.MediaSource
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.VolumeUtils
import com.rabbit.videoplayer.dialog.ShowMoreDialog
import com.rabbit.videoplayer.listener.*
import com.rabbit.videoplayer.listener.player.*
import com.rabbit.videoplayer.response.AliyunShowMoreValue
import com.rabbit.videoplayer.response.PlayerType
import com.rabbit.videoplayer.response.VideoPlayModel
import com.rabbit.videoplayer.tools.Constants
import com.rabbit.videoplayer.tools.VideoPlayerSPUtil
import com.rabbit.videoplayer.widget.*
import com.rabbit.videoplayer.widget.gesture.GestureDialogManager
import com.rabbit.videoplayer.widget.gesture.GestureView
import com.rabbit.videoplayer.widget.player.AliyunRenderView
import com.rabbit.videoplayer.widget.player.Media3PlayerView
import com.rabbit.videoplayer.widget.player.TXPlayerView
import com.tencent.rtmp.TXLiveBase
import com.tencent.rtmp.TXLiveBaseListener
import java.lang.ref.WeakReference
import kotlin.math.absoluteValue
import androidx.core.view.isVisible

@UnstableApi
class MixPlayerView(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {

    companion object {

        fun initPlayer(context: Context, @PlayerType defaultPlayer: Int, isUseAli: Boolean = false, isUseTX: Boolean = false){
            VideoPlayerSPUtil.instance.playerType = defaultPlayer
            VideoPlayerSPUtil.instance.isAllowUseAliPlayer = isUseAli

            val isFinalUseTX = defaultPlayer == PlayerType.TX || isUseTX
            VideoPlayerSPUtil.instance.isAllowUseTXPlayer = isFinalUseTX
            if (isUseTX) {
                try {
                    // 若您服务全球用户， 配置 SDK 接入环境为全球接入环境
                    TXLiveBase.setGlobalEnv("GDPR")
                    val licenceURL = ResourceUtils.readAssets2String("tx_licence_url.cer") // 获取到的 licence url
                    val licenceKey = ResourceUtils.readAssets2String("tx_licence_key.crt") // 获取到的 licence key
                    TXLiveBase.getInstance().setLicence(context, licenceURL, licenceKey)
                    TXLiveBase.setListener(object : TXLiveBaseListener() {
                        override fun onLicenceLoaded(result: Int, reason: String) {
                            Log.e("TXPlayer", "鉴权 result:$result, reason: $reason")
                        }
                    })
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                // tx日志设置
//                TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_WARN)
            }
        }

        /**
         * 播放器信息监听
         */
        private class VideoPlayerOnInfoListener(playerView: MixPlayerView) : OnInfoListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onInfo(code: Int, value: Long) {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodInfoDistribute(code, value)
            }
        }

        /**
         * 播放器信息监听
         */
        private class VideoPlayerPreparedListener(playerView: MixPlayerView) : OnPreparedListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onPrepared() {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodPrepared()
            }
        }

        /**
         * 播放器第一帧显示
         */
        private class VideoPlayerRenderingStartListener(playerView: MixPlayerView) : OnRenderingStartListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onRenderingStart() {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodFirstFrameStart()
            }
        }

        /**
         * 播放器尺寸
         */
        private class VideoPlayerVideoSizeChangedListener(playerView: MixPlayerView) : OnVideoSizeChangedListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onVideoSizeChanged(width: Int, height: Int) {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.ovVodSizeChanged(width, height)
            }
        }

        /**
         * 播放器加载状态
         */
        private class VideoPlayerLoadingStatusListener(playerView: MixPlayerView) : OnLoadingStatusListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }

            // 开始加载。画面和声音不足以播放。
            override fun onLoadingBegin() {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodLoadingBegin()
            }

            // 加载进度。百分比和网速。
            override fun onLoadingProgress(percent: Int, netSpeed: Float) {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodLoadingProgress(percent)
            }

            // 结束加载。画面和声音可以播放。
            override fun onLoadingEnd() {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodLoadingEnd()
            }
        }

        /**
         * 播放器出错
         */
        private class VideoPlayerErrorListener(playerView: MixPlayerView) : OnErrorListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onError(msg: String) {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodError(msg)
            }
        }

        /**
         * 播放完成
         */
        private class VideoPlayerCompleteListener(playerView: MixPlayerView) : OnCompletionListener {
            private val weakReference by lazy { WeakReference<MixPlayerView>(playerView) }
            override fun onCompletion() {
                val aliyunPlayerView = weakReference.get() ?: return
                aliyunPlayerView.onVodComplete()
            }
        }
    }


    //播放器+渲染的View
    private  var mIMixPlayer: IMixPlayer? = null

    private val mGestureView by lazy { GestureView(context) }

    // 播放器控制层
    private val mControlView by lazy { ControlView(context) }

    // 播放器封面图
    private val mCoverView by lazy { CoverView(context) }

    // 播放器出错
    private val mErrorStatusView by lazy { ErrorStatusView(context) }

    // 广告view
    private val mAdView by lazy { AdView(context) }

    // 投屏
    private val mCastScreenView by lazy { CastScreenView(context) }

    // 加载状态
    private val mLoadingView by lazy { LoadStatusView(context) }

    private var dialogHandler: DialogHandler? = null
    /** 更多Dialog */
    private var showMoreDialog: ShowMoreDialog? = null
    // media3的DataSource
    private var mediaSourceFactory: MediaSource.Factory? = null

    // 当前播放器类型
    private var playerType = -1
    // 当前音量
    private var currentVolume = -1
    //当前屏幕亮度
    private var mScreenBrightness = 50
    // 起播时间
    private var startPosition = 0L
    // 当前的下载速度
    private var currentDownloadSpeed = 0L
    // 延迟隐藏控制栏时间
    private val delayHideControlTime = 3500L
    // 挂起
    private var isVodSuspend = false
    // 是否全屏
    private var isFullScreenStatus = false
    // 是否要隐藏其他播放器
    private var isHideOtherPlayers = false
    // 当前是否播放下载的视频
    private var isPlayDownloadVideo = false
    // 播放url
    private var videoUrl: String? = null
    // 播放地址header
    private var headerMap: Map<String, String>? = null
    // 长按快进之前的倍速
    private var speedBeforeLongPress = SpeedValue.One.value
    //手势对话框控制
    private var mGestureDialogManager: GestureDialogManager? = null
    // 初始化音量
    private val initVolume by lazy { VolumeUtils.getVolume(AudioManager.STREAM_MUSIC) }
    // 最大音量
    private val maxVolumeValue by lazy { VolumeUtils.getMaxVolume(AudioManager.STREAM_MUSIC) }

    /****************************************** 外部回调 **************************************/
    // 播放器出错
    private var onVideoErrorListener: OnVodErrorListener? = null
    // 投屏回调
    private var onCastScreenListener: OnCastScreenListener? = null
    private var onVideoPreparedListener: OnPreparedListener? = null
    // 播放器播放完成
    private var onVodCompleteListener: OnVodCompleteListener? = null
    // 加载暂停广告
    private var onLoadPauseAdListener: OnAdReadyLoadListener? = null
    // 加载解锁广告
    private var onLoadUnlockAdListener: OnLoadUnlockAdListener? = null
    // 选集或播放下一集毁掉
    private var vodChangeEpisodeListener: OnChangeEpisodeListener? = null
    private var onVideoSizeChangeListener: OnVideoSizeChangeListener? = null
    // 准备切换线路
    private var onVodChangeSourceListener: OnVodChangeSourceListener? = null
    // 全屏状态监听
    private var onFullScreenStatusListener: OnFullScreenStatusListener? = null
    // 控制器的显示状态
    private var onControlViewStatusListener: OnControlViewStatusListener? = null
    // 长按快进
    private var onLongPressFastForwardListener: OnLongPressFastForwardListener? = null

    // 返回处理
//    private val onBackPress = object : OnBackPressedCallback(true) {
//        override fun handleOnBackPressed() {
//            onVodBackPress()
//        }
//    }

    init {
        setBackgroundColor(Color.BLACK)
        initVideoView()
        // 添加回调对象
//        (context as AppCompatActivity).onBackPressedDispatcher.addCallback(context, onBackPress)
        currentVolume = initVolume
    }

    /** 初始化播放器需要的各个控件 */

    private fun initVideoView() {
        keepScreenOn = true
        // 初始化手势层
        initGestureView()
        // 初始化播放器控制层
        initControlView()
        // 初始化封面
        initCoverView()
        // 初始化出错View
        initErrorView()
        // 初始化广告view
        initAdView()
        // 初始化投屏
        initCastScreenView()
        // 显示加载状态
        initLoadingView()
        // 初始化手势dialog控制器
        initGestureDialogManager()
        // 设置亮度
        mScreenBrightness = getCurrentBrightValue()

        dialogHandler = DialogHandler(this)
    }


    // 返回当前播放器类型
    private fun getPlayerByType(playerType: Int): IMixPlayer {
        return if (playerType == PlayerType.ALIYUN && VideoPlayerSPUtil.instance.isAllowUseAliPlayer) {
            AliyunRenderView(context)
        } else if (playerType == PlayerType.TX && VideoPlayerSPUtil.instance.isAllowUseTXPlayer) {
            TXPlayerView(context)
        } else {
            Media3PlayerView(context)
        }
    }

    /**
     * 初始化播放器 + 渲染的View
     * 播放器处在最底层
     */
    private fun initMixPlayer(playerType: Int = -1) {
        mIMixPlayer = if (playerType == -1) {
            getPlayerByType(VideoPlayerSPUtil.instance.playerType)
        } else {
            getPlayerByType(playerType)
        }
        // 初始化播放器的配置, 播放器永远在最底层
        val videoPlayer = mIMixPlayer?.initPlayer(context)
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        params.startToStart = LayoutParams.PARENT_ID
        params.topToTop = LayoutParams.PARENT_ID
        //添加到布局中
        addView(videoPlayer, 0, params)
        // 播放器出错监
        mIMixPlayer?.setOnErrorListener(VideoPlayerErrorListener(this))
        // 播放信息监听 比如缓冲进度，播放进度等
        mIMixPlayer?.setOnInfoListener(VideoPlayerOnInfoListener(this))
        // 设置准备回调
        mIMixPlayer?.setOnPreparedListener(VideoPlayerPreparedListener(this))
        //播放结束
        mIMixPlayer?.setOnCompletionListener(VideoPlayerCompleteListener(this))
        // 播放器加载回调
        mIMixPlayer?.setOnLoadingStatusListener(VideoPlayerLoadingStatusListener(this))
        // 第一帧显示
        mIMixPlayer?.setOnRenderingStartListener(VideoPlayerRenderingStartListener(this))

        mIMixPlayer?.setOnVideoSizeChangedListener(VideoPlayerVideoSizeChangedListener(this))
    }


    /**
     * 初始化手势
     */
    private fun initGestureView() {
        addSubView(mGestureView)
        mGestureView.setOnGestureListener(object : GestureView.GestureListener {
            // 是否长按中
            private var isInLongPress = false

            // 是否竖向滑动中
            private var isInVerticalSeek = false

            // 是否横向滑动中
            private var isInHorizontalSeek = false
            override fun onHorizontalDistance(downX: Float, nowX: Float) { // 先onHorizontalDistance xxx(重复多次) 再onGestureEnd
                // seek需要在手势结束时操作。
                isInHorizontalSeek = true
                val duration: Long = mIMixPlayer?.getDuration()?:0L
                val position: Long = mIMixPlayer?.getCurrentPosition()?:0L
                var targetPosition = 0L
                if (mIMixPlayer?.isPrepared() == true) {
                    //在播放时才能调整大小
                    val deltaPosition = (nowX - downX).toLong() * duration / width
                    targetPosition = getTargetPosition(duration, position, deltaPosition)
                }
                clearDelayHide()
                mControlView.showOnlySeekBar(targetPosition)
            }

            override fun onLeftVerticalDistance(downY: Float, nowY: Float) {
                isInVerticalSeek = true
                //左侧上下滑动调节亮度
                val changePercent = ((nowY - downY) * 100 / height).toInt()
                if (mGestureDialogManager != null) {
                    mGestureDialogManager!!.showBrightnessDialog(this@MixPlayerView, mScreenBrightness)
                    val brightness = mGestureDialogManager!!.updateBrightnessDialog(changePercent)
                    mScreenBrightness = brightness
                    setWindowBrightness(mScreenBrightness)
                }
            }

            override fun onRightVerticalDistance(downY: Float, nowY: Float) {
                isInVerticalSeek = true
                isInVerticalSeek = true
                //右侧上下滑动调节音量
                // 当前音量
                val current = mGestureDialogManager?.currentVolume?:0f
//                Log.e("Player", "当前音量：$current, 最大音量：$maxVolumeValue")
                // 当前的音量百分比
                val percent = current * 1f / maxVolumeValue
//                Log.e("Player", "当前音量：$current, 最大音量：$maxVolumeValue，当前百分比：$percent")
                // 能滑动最大高度
                val maxHeight = height
                // 当前滑动距离, 负数增加音量，正数降低音量
                val scrollY = nowY - downY
//                Log.e("Player", "当前滑动距离百分比：$scrollYPercent")
                var finalPercent = if (scrollY < 0) {
                    scrollY.absoluteValue * 1f / maxHeight + percent
                } else {
                    percent - scrollY.absoluteValue * 1f / maxHeight
                }
                if (finalPercent > 1f) {
                    finalPercent = 1f
                } else if (finalPercent < 0) {
                    finalPercent = 0f
                }
//                Log.e("Player", "当前初始出发位置：$downY, 当前滑动到位置：$nowY, 滑动距离：${nowY - downY}, 最大高度：$maxHeight, 滑动百分比：$finalPercent")
                // 当前改变音量
                val finalVolume = finalPercent * maxVolumeValue
                // 更新dialog的百分比
                mGestureDialogManager?.showVolumeDialog(this@MixPlayerView, finalPercent * 100)
                // 设置当前的音量
                VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, finalVolume.toInt(), 0)
            }

            override fun onGestureEnd() {
                if (isInLongPress) {
                    isInLongPress = false
                    onVodLongPressScreen(false)
                    return
                }

                if (isInHorizontalSeek) {
                    isInHorizontalSeek = false
                    val seekTo = mControlView.hideOnlySeekBar()
                    mIMixPlayer?.seekTo(seekTo)
                    delayHideControl()
                }

                if (isInVerticalSeek) {
                    isInVerticalSeek = false
                    mGestureDialogManager?.dismissBrightnessDialog()
                    mGestureDialogManager?.dismissVolumeDialog()
                }
            }

            // 单击
            override fun onSingleTap() { // 先onGestureEnd 再onSingleTap
                onVodSwitchDisplayControlView()
            }

            // 双击
            override fun onDoubleTap() { // 先onGestureEnd 再onDoubleTap 再onGestureEnd
                switchPlayOrPause(true)
            }

            // 长安快进
            override fun onLongPress() { // 先onLongPress 再onGestureEnd
                isInLongPress = true
                onVodLongPressScreen(true)
            }
        })
    }

    /**
     * 是否全屏显示线路按钮
     */
    fun setFullScreenSourceSwitch(isDisplaySourceSwitch: Boolean){
        mControlView.setFullScreenSourceSwitch(isDisplaySourceSwitch)
    }

    /**
     * 初始化播放器的控制层，包括标题，进度，播放按钮等
     */
    @Suppress("DEPRECATION")
    private fun initControlView() {
        addSubView(mControlView)
        mControlView.setControlClickCallback(object : ControlView.OnControlClickCallback {

            override fun onBack() {
                // 隐藏其他窗口
//                onVodBackPress()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    (context as Activity).onBackInvokedDispatcher
                } else {
                    (context as Activity).onBackPressed()
                }
            }

            override fun showMore() {
                showVideoSettingDialog()
            }

            override fun showEpisodeList() {
                onVodEpisodeSelected()
            }

            override fun playNext(): Boolean {
                return vodChangeEpisodeListener?.onPlayNext() ?: true
            }

            override fun switchPlay() {
                switchPlayOrPause()
            }

            override fun switchLock(isLockedScreen: Boolean) {
                onVodLockedScreen(isLockedScreen)
            }

            override fun switchFullScreen(isFullScreen: Boolean) {
                onVodFullScreen(isFullScreen)

            }

            override fun castScreen() {
                onCastScreenListener?.onCastScreen()
            }

            override fun isStartTrackingTouch(isTouchOn: Boolean) {
                onVodSeekBarTouchOn(isTouchOn)
            }

            override fun seekTo(progress: Long) { // 无需修改ui
                val duration = mIMixPlayer?.getDuration()?:0L
                mIMixPlayer?.seekTo(
                    if (progress >= duration) { // 优化seek
                        progress - 10000
                    } else {
                        progress
                    }
                )
            }

            override fun changeSource() {
                onVodChangeSourceListener?.onChangeSource()
            }

        })
    }


    /** 初始化封面 */
    private fun initCoverView() {
        addSubView(mCoverView)
    }

    /** 初始播放出错 */
    private fun initErrorView() {
        addSubView(mErrorStatusView)
        mErrorStatusView.setErrorStatusListener(object : OnErrorStatusListener {
            override fun onRetry() { // 尝试重新播放
                onVideoErrorListener?.onRetry()
            }

            override fun onCancel() {
            }
        })
    }

    /** 初始化广告view */
    private fun initAdView() {
        mAdView.setLoadUnlockAdListener(object : OnLoadUnlockAdListener {
            override fun onLoadUnlockAd() {
                onLoadUnlockAdListener?.onLoadUnlockAd()
            }
        })
        mAdView.setReady2AdListener(object: OnAdReadyLoadListener {
            override fun onReady2LoadAd() {
                onLoadPauseAdListener?.onReady2LoadAd()
            }
        })
        addSubView(mAdView)
    }

    fun hidePauseAd(){
        mAdView.onAdLoadFailed()
    }

    fun showPauseAd(): ViewGroup?{
        return mAdView.onAdLoaded()
    }

    /** 初始化投屏 */
    private fun initCastScreenView() {
        mCastScreenView.setCastScreenListener(object : OnCastScreenListener {
            override fun onCastScreen() {}

            override fun onCloseCastScreen() {
                onCastScreenListener?.onCloseCastScreen()
            }

            override fun onCastScreenPlay(): Boolean {
                return onCastScreenListener?.onCastScreenPlay() ?: false
            }

            override fun seekTo(seek: Long) {
                onCastScreenListener?.seekTo(seek)
            }

            override fun isStartTrackingTouch(isTouchOn: Boolean) {
                onCastScreenListener?.isStartTrackingTouch(isTouchOn)
            }
        })
        addSubView(mCastScreenView)
    }

    /** 初始化加载状态 */
    private fun initLoadingView() {
        addSubView(mLoadingView)
    }


    /**
     * 播放器OnInfo分发处理
     */
    private fun onVodInfoDistribute(code: Int, value: Long) {
        // 当前进度：InfoCode.CurrentPosition
        // 当前缓存位置：InfoCode.BufferedPosition
        // extraValue为当前缓冲进度，单位为毫秒
        // 挂起后不在处理消息分发
        if (isVodSuspend) return
        when (code) {
            Constants.INFO_CODE_CURRENT_POSITION -> { // 当前进度条
                if (mControlView.isSeekBarOnTouch) return
                mControlView.setCurrentPosition(value)
            }

            Constants.INFO_CODE_BUFFERED_POSITION -> { // 缓冲进度
                if (mControlView.isSeekBarOnTouch) return
                mControlView.setBufferedPosition(value)
            }

            Constants.INFO_CODE_CURRENT_DOWNLOAD_SPEED -> { // 当前下载速度
                currentDownloadSpeed = value
            }
            else -> {}
        }
    }



    /** 视频初始化 */
    private fun onVodInit(
        url: String,
        title: String?,
        startPosition: Long = 0L,
        headerMap: Map<String, String>? = null
    ) {
        videoUrl = url
        this.headerMap = headerMap
        this.startPosition = startPosition
        clearDelayHide()
        // 控制器层进入init状态
        mControlView.onVodInit(title)
        // 设置封面
        mCoverView.onVodInit()
        mCastScreenView.onVodInit()
        // 判断4g和网络，下载视频无需此判断
        if (!isPlayDownloadVideo) {
            val isError = mErrorStatusView.onVodInit()
            if (isError) {
                mLoadingView.hide()
                return
            }
        }

        if (playerType == -1) { // 无需改动播放器
            if (mIMixPlayer == null) {
                initMixPlayer()
            }
        } else { // 需要根据当前的播放器类型处理
            if (mIMixPlayer == null) {
                initMixPlayer(playerType = playerType)
            } else {
                if (playerType != mIMixPlayer?.getPlayerType()) {
                    // 当前的播放速度
                    val currentSpeed = mIMixPlayer?.getSpeed()?:1f
                    mIMixPlayer?.onVodRelease()
                    removeViewAt(0)
                    initMixPlayer(playerType = playerType)
                    // 恢复倍速
                    mIMixPlayer?.setSpeed(currentSpeed)
                }
            }
        }
        mIMixPlayer?.setAutoPlay(false)
        // 初始化播放器
        mIMixPlayer?.onVodInit(url, startPosition, headerMap, isPlayDownloadVideo, mediaSourceFactory)
        // 根据播放器类型，显示加载状态
        mLoadingView.onVodInit(mIMixPlayer?.getPlayerType())
    }

    /** 视频准备完成 */
    private fun onVodPrepared() {
        val duration = mIMixPlayer?.getDuration()?:0L
        // 进入装备状态
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodPrepared(startPosition, duration)
        }
        // 播放器回调
        onVideoPreparedListener?.onPrepared()

//        // 除了播放器，其他都进入播放状态
//        ready2StartVideo()
    }

    /** 视频进入Start状态 */
    private fun onVodStarted() {
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodStart()
        }
    }

    /** 视频第一帧开始显示 */
    private fun onVodFirstFrameStart() {
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodFirstFrameStart()
        }
        // 延迟隐藏对话框
        delayHideControl()
    }

    // 默认以宽为基准
    private var videoOriginWidth = -1
    private var videoOriginHeight = -1
    private var currentPlayerRadio = "2:1"
    private var isUseVideoScaleAnimation = true

    fun setUseVideoScaleAnimation(isUseVideoScaleAnimation: Boolean){
        this.isUseVideoScaleAnimation = isUseVideoScaleAnimation
    }


    private fun ovVodSizeChanged(width: Int, height: Int) {
        Log.e("视频尺寸调整", "ovVodSizeChanged: $width x $height")
        if (width == 0 || height == 0) return
        // 初始尺寸调整
        videoOriginWidth = width
        videoOriginHeight = height
        // 播放器Parent的比例
        currentPlayerRadio = "$videoOriginWidth:$videoOriginHeight"
        if (isFullScreenStatus) { // 可能因为切换播放器导致重新加载
            val scaleMode = mControlView.getScaleMode()
            setScaleMode(scaleMode)
        } else if(videoPlayModel == VideoPlayModel.SKITS) { // 短剧
            // 设置缩放，按默认的自适应来适配短剧模式
            setScaleMode(Constants.VIDEO_RESIZE_FIT)
        } else { // 非全屏，比如刚进入播放页面
//            val mixPlayerViewLayoutParams = this.layoutParams as LayoutParams
//            mixPlayerViewLayoutParams.height = 0
//            mixPlayerViewLayoutParams.dimensionRatio = currentPlayerRadio
//            this.layoutParams = mixPlayerViewLayoutParams
//            // 修改播放器的比例
//            val playerView = getMixPlayer()?:return
//            val playerViewLayoutParams = playerView.layoutParams as LayoutParams
//            scaleVideoFit(playerViewLayoutParams)

            if (isUseVideoScaleAnimation) {
                // 等没问题了用新方案
                val targetScale = videoOriginWidth * 1f / videoOriginHeight
                if (BuildConfig.DEBUG) {
//                Log.e("视频尺寸调整", "进行初始尺寸调整 -> ${mixPlayerViewLayoutParams.dimensionRatio}")
                    Log.e("视频尺寸调整", "targetScale -> ${targetScale}")
                }
                val originHeight = this.height
                val targetHeight = (this.width * 1f / targetScale).toInt()
//            Log.e("视频尺寸调整", "originHeight -> ${originHeight}")
//            Log.e("视频尺寸调整", "targetHeight -> ${targetHeight}")
                val animator = ValueAnimator.ofInt(originHeight, targetHeight)
                animator.addUpdateListener { p0 ->
                    val value = p0.animatedValue as Int
                    val mixPlayerViewLayoutParams = this.layoutParams as ConstraintLayout.LayoutParams
                    mixPlayerViewLayoutParams.height = value // 更新高度值
                    this.layoutParams = mixPlayerViewLayoutParams // 应用新的布局参数
                }

                animator.addListener(object: Animator.AnimatorListener {
                    override fun onAnimationCancel(p0: Animator) {
                        doSomethingEnd()
                    }

                    override fun onAnimationEnd(p0: Animator) {
                        doSomethingEnd()
                    }

                    private fun doSomethingEnd(){
                        animator.removeAllUpdateListeners()
                        val mixPlayerViewLayoutParams = this@MixPlayerView.layoutParams as LayoutParams
                        mixPlayerViewLayoutParams.height = 0
                        mixPlayerViewLayoutParams.dimensionRatio = currentPlayerRadio
                        this@MixPlayerView.layoutParams = mixPlayerViewLayoutParams // 应用新的布局参数

                        val playerView = getMixPlayer()?:return
                        val playerViewLayoutParams = playerView.layoutParams as LayoutParams
                        scaleVideoFit(playerViewLayoutParams)
                    }

                    override fun onAnimationRepeat(p0: Animator) {
                    }

                    override fun onAnimationStart(p0: Animator) {
                    }
                })

                animator.duration = 250 // 设置动画时长
                animator.start() // 开始动画
            }
        }

        onVideoSizeChangeListener?.onVideoSizeChange(width, height)
    }

    /** 视频进入Pause状态 */
    private fun onVodPaused() {
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodPause()
        }
        vodChangeEpisodeListener?.onPause()
    }

    /** 播放器切换显示或隐藏控制栏 */
    private fun onVodSwitchDisplayControlView() {
        // 无论是显示还是隐藏，都不在需要延迟处理了
        clearDelayHide()
        if (mControlView.isVisible) {
            mControlView.hide()
            onControlViewStatusListener?.onControlViewStatus(false)
        } else {
            mControlView.show()
            delayHideControl()
            onControlViewStatusListener?.onControlViewStatus(true)
        }
    }

    /** 锁屏状态 */
    fun onVodLockedScreen(isLockedScreen: Boolean) {
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodLockedScreen(isLockedScreen)
        }
        // 点击按钮会再次推迟延迟隐藏
        delayHideControl()
    }


    /** 当长按屏幕的时候 */
    fun onVodLongPressScreen(isShowLongPressUI: Boolean) {
        if (isShowLongPressUI) {
            clearDelayHide()
            mControlView.hide()
            mGestureView.showLongPressFast()
            speedBeforeLongPress = mIMixPlayer?.getSpeed()?:1f
            mIMixPlayer?.setSpeed(SpeedValue.Third.value)
        } else {
            mGestureView.hideLongPressFast()
            mIMixPlayer?.setSpeed(speedBeforeLongPress)
            mControlView.setSpeed(speedBeforeLongPress)
        }
        onLongPressFastForwardListener?.onLongPressFastForwardListener(isShowLongPressUI)
    }

    /** 锁屏状态 */
    @Suppress("DEPRECATION")
    fun onVodFullScreen(isFullScreen: Boolean) {
        isFullScreenStatus = isFullScreen
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodFullScreen(isFullScreen)
        }
        if (context is Activity) {
            val activity = context as Activity
            if (isFullScreen) {
                //设置view的布局，宽高
                val playerLayoutParams = layoutParams as LayoutParams
                playerLayoutParams.dimensionRatio = null
                playerLayoutParams.bottomToBottom = LayoutParams.PARENT_ID

                val controller = WindowCompat.getInsetsController(activity.window, this)
                controller.hide(WindowInsetsCompat.Type.systemBars())
                controller.hide(WindowInsetsCompat.Type.navigationBars())
                controller.systemBarsBehavior = BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE

                activity.window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
                )
                if (activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
                    activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                }
            } else {
                //设置view的布局，宽高之类
                val aliVcVideoViewLayoutParams = layoutParams as LayoutParams
                aliVcVideoViewLayoutParams.bottomToBottom = LayoutParams.UNSET
                aliVcVideoViewLayoutParams.dimensionRatio = currentPlayerRadio

                //不是固定竖屏播放。
                if (activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
                    activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
                }
                val controller =  WindowCompat.getInsetsController(activity.window, this)
                controller.show(WindowInsetsCompat.Type.systemBars())
                controller.show(WindowInsetsCompat.Type.navigationBars())
                controller.systemBarsBehavior = BEHAVIOR_DEFAULT
            }
        }
        // 点击按钮会再次推迟延迟隐藏
        delayHideControl()
        // 设置全屏监听
        onFullScreenStatusListener?.onFullScreen(isFullScreen)
    }


    /** 锁屏状态 */
    fun onVodSeekBarTouchOn(isTouchOn: Boolean) {
        if (isTouchOn) { // 此时手指按在进度条上，应该停止延迟隐藏控制栏和进度
            clearDelayHide()
        } else {
            delayHideControl()
        }
    }

    /**
     * 播放器出错
     */
    fun onVodError(errorInfo: String) {
        val showErrorUI = onVideoErrorListener?.onVodError(errorInfo) ?: true
        if (!showErrorUI) return
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodError(errorInfo)
        }
    }

    fun retry(){
        // 重启播放
        clearDelayHide()
        // 判断4g和网络
        if (!isPlayDownloadVideo) {
            val isError = mErrorStatusView.onVodInit()
            if (isError) {
                mLoadingView.hide()
                return
            }
        }
        // 播放器设置到初始状态
        mIMixPlayer?.onVodInit(videoUrl, startPosition, headerMap, isPlayDownloadVideo, mediaSourceFactory)
        mLoadingView.onVodInit(mIMixPlayer?.getPlayerType())
        dialogHandler?.sendEmptyMessage(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
    }

    fun getPlayerType(): Int {
        return mIMixPlayer?.getPlayerType()?:PlayerType.MEDIA3
    }
    /**
     * 切换播放器
     */
    fun switchPlayer(@PlayerType currentPlayer: Int){
        if (mIMixPlayer == null) return
        if (mIMixPlayer?.getPlayerType() == currentPlayer) return
        startPosition = getCurrentPosition()
        val speedValue = mIMixPlayer?.getSpeed()?:1f
        mIMixPlayer?.onVodRelease()
        removeViewAt(0)
        // 初始化播放器
        initMixPlayer(playerType = currentPlayer)
        mIMixPlayer?.setSpeed(speedValue)
        retry()
    }

    /**
     * 播放器完成播放
     */
    private fun onVodComplete() {
        // 播放完成，起播位置默认初始化
        startPosition = 0
        val isShowCompleteUI = onVodCompleteListener?.onVodComplete() ?: true
        if (!isShowCompleteUI) {
            clearDelayHide()
            mControlView.showCompleteAndReadyToPlayNext()
            return
        }
        // 执行播放完成逻辑
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodComplete()
        }
    }

    /**
     * 在播放器页面返回
     */
    fun canBackPress(): Boolean {
        if (showMoreDialog?.isShowing == true) {
            hideMoreDialog()
            return false
        }
        if (mControlView.onVodBackPress() && videoPlayModel == VideoPlayModel.NORMAL) {
            onVodFullScreen(false)
            return false
        }

        if (mCastScreenView.isShowing()) {
            mCastScreenView.closeCastScreen()
            return false
        }
        return true
    }

//    /**
//     * 在播放器页面返回
//     */
//    private fun onVodBackPress() {
//        if (showMoreDialog?.isShowing == true) {
//            hideMoreDialog()
//            return
//        }
//        if (mControlView.onVodBackPress() && videoPlayModel == VideoPlayModel.NORMAL) {
//            onVodFullScreen(false)
//            return
//        }
//
//        if (mCastScreenView.isShowing()) {
//            mCastScreenView.closeCastScreen()
//            return
//        }
//
//        (context as Activity).finish()
//    }

    /** 开始加载状态 */
    private fun onVodLoadingBegin() {
        mLoadingView.onVodLoadingBegin()
    }

    /** 加载状态更新进度中 */
    private fun onVodLoadingProgress(percent: Int) {
        // 获取当前的网络下行码率，数据类型为Float，单位为bps。
        mLoadingView.onVodLoadingProgress(percent, currentDownloadSpeed)
    }

    /** 结束加载状态 */
    private fun onVodLoadingEnd() {
        mLoadingView.onVodLoadingEnd()
    }

    /** 切换选集 */
    private fun onVodEpisodeSelected() {
        // 隐藏其他控制栏
        clearDelayHide()
        mControlView.onEpisodeSelected()
        vodChangeEpisodeListener?.showEpisodeList()
    }



    /**=================================== 播放器的常用方法 =====================================*/
    /**
     * 播放视频
     * @param url 视频地址
     * @param title 视频标题
     * @param startPosition 开始播放的初始位置
     * @param isPlayDownloadVideo 当前视频是否是下载视频
     * @param headerMap 视频地址的header
     * @param playerType 指定播放器类型
     * @param isHideOtherPlayers 是否要隐藏其他播放器 默认false
     */
    fun playVideo(
        url: String,
        title: String?,
        startPosition: Long = 0L,
        isPlayDownloadVideo: Boolean = false,
        headerMap: Map<String, String>? = null,
        playerType: Int = -1,
        isHideOtherPlayers: Boolean = false
    ) {
        // 清空数据
        try {
            clearData()
            // 先停止播放视频
            mIMixPlayer?.stop()
            mAdView.onVodRelease()
            this.playerType = playerType
            this.isPlayDownloadVideo = isPlayDownloadVideo
            this.isHideOtherPlayers = isHideOtherPlayers
            Log.d("Mix播放器", "title:$title, isPlayDownloadVideo:$isPlayDownloadVideo, playerType:$playerType, isHideOtherPlayers:$isHideOtherPlayers")
            onVodInit(url, title, startPosition, headerMap)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 设置剧集列表信息
    fun setVideoEpisodeData(currentPlayIndex: Int, episodeSize: Int){
        // 控制器层进入init状态
        mControlView.setVideoEpisodeData(currentPlayIndex, episodeSize)
    }

    fun setMediaSourceFactory(mediaSourceFactory: MediaSource.Factory) {
        this.mediaSourceFactory = mediaSourceFactory
    }

    fun showErrorStatus(msg: String) {
        mLoadingView.hide()
        mIMixPlayer?.stop()
        mCoverView.show()
        mAdView.onVodRelease()
        mCastScreenView.closeCastScreen()
        mErrorStatusView.showErrorStatus(msg)
    }

    /**
     * 设置线路名称
     */
    fun setSourceName(name: String) {
        mControlView.setSourceName(name)
    }

    /**
     * 设置视频播放模式
     *  普通模式
     *  全屏模式
     */
    @VideoPlayModel
    private var videoPlayModel: Int = VideoPlayModel.NORMAL
    fun setVideoModel(@VideoPlayModel model: Int){
        videoPlayModel = model
        if (model == VideoPlayModel.FULL_SCREEN) { // 默认全屏模式
            isFullScreenStatus = true
            for (index in 0 until childCount) {
                val child = getChildAt(index) as OnVideoStatusListener
                child.onVodFullScreen(true)
            }
            mControlView.hideFullScreenButton()
        } else if (model == VideoPlayModel.SKITS) {
            for (index in 0 until childCount) {
                val child = getChildAt(index) as OnVideoStatusListener
                child.onVodSkits()
            }
        }
    }

    /** 进入stop播放状态 */
    fun onVodStop() {
        // 清空数据
        clearData()
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodStop()
        }
    }


    /** 视频挂起 */
    fun onVodSuspend() {
        isVodSuspend = true
        if (!isPrepared()) return
        onVodPaused()
    }

    private fun findActivity(context: Context?): Activity? {
        if (context == null) return null
        if (context is Activity) {
            return context
        }
        return if (context is ContextWrapper) {
            findActivity(context.baseContext)
        } else {
            null
        }
    }

    /** 视频恢复 */
    fun onVodResume(canStart: Boolean = true) {
        isVodSuspend = false
        if (!isPrepared() || mErrorStatusView.isShowing() || !canStart) return
        // 判断是否处于投屏页面
        if (mCastScreenView.isShowing()) return
        onVodStarted()
    }

    fun pause() {
        if (!isPrepared()) return
        onVodPaused()
    }


    fun start(){
        if (isVodSuspend || !isPrepared() || mErrorStatusView.isShowing()) return
        onVodStarted()
    }

    /** 显示播放器加载状态 */
    fun showLoadingStatus() {
        mIMixPlayer?.stop()
        mControlView.hide()
        mCoverView.show()
        mErrorStatusView.hide()
        mLoadingView.showLoadingStatus()
    }


    /** 显示解锁UI */
    fun showUnlockUI() {
        // 直接隐藏控制栏
        clearDelayHide()
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodShowUnlockUI(true)
        }
    }

    /**
     * 隐藏解锁UI
     */
    fun hideUnlockUI() {
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodShowUnlockUI(false)
        }
    }


    /**
     * 显示投屏即将连接状态
     * @param deviceName 设备名称
     */
    fun showCastScreenReadyToConnect(deviceName: String) {
        mLoadingView.hide()
        // 暂停视频播放
        mIMixPlayer?.pause()
        // 显示投屏view
        mCastScreenView.showCastScreen(deviceName, getDuration())
    }

    /**
     * 投屏已经连接
     */
    fun showCastScreenConnected() {
        mCastScreenView.showConnected()
    }

    /**
     * 投屏断开连接
     */
    fun showCastScreenDisConnect(msg: String) {
        mCastScreenView.showDisConnect(msg)
    }

    /**
     * 更新投屏的进度
     */
    fun updateCastScreenCurrentPosition(currentPosition: Long) {
        mCastScreenView.updateCurrentPosition(currentPosition)
    }

    /**
     * 切换投屏的播放状态
     */
    fun caseScreenSwitchPlayOrPause(isPlaying: Boolean) {
        mCastScreenView.switchPlayOrPauseUI(isPlaying)
    }

    /**
     * 关闭投屏
     */
    fun closeCastScreen() {
        mIMixPlayer?.start()
    }

    /**
     * 当前正在播放的位置
     */
    fun getCurrentPosition(): Long {
        return mIMixPlayer?.getCurrentPosition()?:0L
    }

    fun getDuration(): Long {
        return mIMixPlayer?.getDuration()?:0L
    }

    /**
     * 返回当前的url
     */
    fun getVodUrl(): String? {
        return videoUrl
    }

    fun isPrepared(): Boolean {
        return mIMixPlayer?.isPrepared()?:false
    }

    /**
     * 释放播放器
     */
    fun release() {
        dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_CONTROL_VIEW)
        dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
        for (index in 0 until childCount) {
            val child = getChildAt(index) as OnVideoStatusListener
            child.onVodRelease()
        }
        removeAllViews()
    }
    /**=================================== 播放器的常用方法 =====================================*/
    /************************************* 设置各种监听方法 **************************************/
    /**
     * 设置剧集点击事件
     */
    fun setVodChangeEpisodeListener(listener: OnChangeEpisodeListener) {
        vodChangeEpisodeListener = listener
    }

    fun setVideoSizeChangeListener(listener: OnVideoSizeChangeListener) {
        onVideoSizeChangeListener = listener
    }


    /**
     * 设置剧集点击事件
     */
    fun setVodPreparedListener(listener: OnPreparedListener) {
        onVideoPreparedListener = listener
    }

    fun setCoverBackgroundResource(@DrawableRes resId: Int){
        mCoverView.setCoverBackgroundResource(resId)
    }

    fun setCoverUrl(coverUrl: String){
        mCoverView.setCoverUrl(coverUrl)
    }

    /**
     * 设置剧集点击事件
     */
    fun setFullScreenStatusListener(listener: OnFullScreenStatusListener) {
        onFullScreenStatusListener = listener
    }

    fun setVodChangeSourceListener(listener: OnVodChangeSourceListener) {
        onVodChangeSourceListener = listener
    }

    /**
     * 设置播放器出错
     */
    fun setVodErrorListener(listener: OnVodErrorListener) {
        onVideoErrorListener = listener
    }

    /**
     * 设置控制器显示隐藏
     */
    fun setOnControlViewStatusListener(listener: OnControlViewStatusListener) {
        onControlViewStatusListener = listener
    }
    /**
     * 设置长按快进
     */
    fun setLongPressFastForwardListener(listener: OnLongPressFastForwardListener) {
        onLongPressFastForwardListener = listener
    }

    /**
     * 设置播放完成事件
     */
    fun setVodCompleteListener(listener: OnVodCompleteListener) {
        onVodCompleteListener = listener
    }

    /**
     * 设置加载解锁广告
     */
    fun setOnLoadUnlockAdListener(listener: OnLoadUnlockAdListener) {
        onLoadUnlockAdListener = listener
    }

    /**
     * 设置加载暂停广告
     */
    fun setOnLoadPauseAdListener(listener: OnAdReadyLoadListener) {
        onLoadPauseAdListener = listener
    }


    /**
     * 设置投屏监听
     */
    fun setCastScreenListener(listener: OnCastScreenListener) {
        onCastScreenListener = listener
    }
    /************************************* 设置各种监听方法 **************************************/

    /** 初始化手势的控制类 */
    private fun initGestureDialogManager() {
        val context = context
        if (context is Activity) {
            mGestureDialogManager = GestureDialogManager(context)
        }
    }

    // 切换播放和暂停
    private fun switchPlayOrPause(isPlayDoubleTap: Boolean = false) {
        val isPlaying = mIMixPlayer?.isPlaying()?:false
        if (isPlaying) {
            onVodPaused()
        } else {
            onVodStarted()
        }
        // 显示或隐藏暂停广告
        mAdView.loadPauseAd(isPlaying)
        if (!isPlayDoubleTap) { // 双击来控制播放和暂停的时候，不需要再隐藏控制栏
            delayHideControl()
        }
    }

    /**
     * addSubView 添加子view到布局中
     * @param view 子view
     */
    private fun addSubView(view: View) {
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        params.startToStart = LayoutParams.PARENT_ID
        params.endToEnd = LayoutParams.PARENT_ID
        params.topToTop = LayoutParams.PARENT_ID
        params.bottomToBottom = LayoutParams.PARENT_ID
        //添加到布局中
        addView(view, params)
    }

    /**
     * 延迟隐藏控制栏
     */
    private fun delayHideControl() {
        dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_CONTROL_VIEW)
        dialogHandler?.sendEmptyMessageDelayed(DialogHandler.MSG_WHAT_HIDE_CONTROL_VIEW, delayHideControlTime)
    }
    /**
     * 清除延迟隐藏控制
     */
    private fun clearDelayHide() {
        dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_CONTROL_VIEW)
    }

    /**
     * 仅当系统的亮度模式是非自动模式的情况下，获取当前屏幕亮度值[0, 255].
     * 如果是自动模式，那么该方法获得的值不正确。
     */
    private fun getCurrentBrightValue(): Int {
        var nowBrightnessValue = 0
        val resolver = context.contentResolver
        try {
            // 0 -255
            nowBrightnessValue = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS, 255)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return nowBrightnessValue
    }

    /**
     * 设置屏幕亮度
     */
    private fun setWindowBrightness(brightness: Int) {
        if (context !is Activity) return
        val window = (context as Activity).window
        val lp = window.attributes
        lp.screenBrightness = brightness / 100.00f
        window.attributes = lp
    }

    /**
     * 目标位置计算算法
     *
     * @param duration        视频总时长
     * @param currentPosition 当前播放位置
     * @param deltaPosition   与当前位置相差的时长
     * @return
     */
    private fun getTargetPosition(duration: Long, currentPosition: Long, deltaPosition: Long): Long {
        // seek步长
        val finalDeltaPosition: Long
        // 根据视频时长，决定seek步长
        val totalMinutes = duration / 1000 / 60
        val hours = (totalMinutes / 60).toInt()
        val minutes = (totalMinutes % 60).toInt()
        // 视频时长为1小时以上，小屏和全屏的手势滑动最长为视频时长的十分之一
        finalDeltaPosition = if (hours >= 1) {
            deltaPosition / 10
        } // 视频时长为31分钟－60分钟时，小屏和全屏的手势滑动最长为视频时长五分之一
        else if (minutes > 30) {
            deltaPosition / 5
        } // 视频时长为11分钟－30分钟时，小屏和全屏的手势滑动最长为视频时长三分之一
        else if (minutes > 10) {
            deltaPosition / 3
        } // 视频时长为4-10分钟时，小屏和全屏的手势滑动最长为视频时长二分之一
        else if (minutes > 3) {
            deltaPosition / 2
        } // 视频时长为1秒钟至3分钟时，小屏和全屏的手势滑动最长为视频结束
        else {
            deltaPosition
        }
        var targetPosition = finalDeltaPosition + currentPosition
        if (targetPosition < 0) {
            targetPosition = 0
        }
        if (targetPosition > duration) {
            targetPosition = duration - 5
        }
        return targetPosition
    }


    private fun hideMoreDialog() {
        if (showMoreDialog != null) {
            showMoreDialog?.dismiss()
        }
    }



    /**
     * 显示更多弹窗
     */
    fun showVideoSettingDialog() {
        if (context !is Activity) return
        val activity = context as Activity
        if (activity.isFinishing || activity.isDestroyed) return
        if (showMoreDialog == null) {
            showMoreDialog = ShowMoreDialog(activity)
            val showMoreView = ShowMoreView(activity)
            showMoreDialog?.contentView = showMoreView
            showMoreView.setOnMoreViewCheckedChangedListener(object : ShowMoreView.OnMoreViewCheckedChangedListener {
                override fun onScaleModeChanged(mScaleMode: Int) {
                    setScaleMode(mScaleMode)
                    // 延迟隐藏
                    delayHideMoreDialog()
                }

                override fun onSpeedChanged(speedValue: SpeedValue) {
                    mControlView.setSpeed(speedValue)
                    mIMixPlayer?.setSpeed(speedValue.value)
                    // 延迟隐藏
                    delayHideMoreDialog()
                }


                override fun onLoopChanged(isLoop: Boolean) {
                    mIMixPlayer?.setLoop(isLoop)
                    // 延迟隐藏
                    delayHideMoreDialog()
                }

                override fun onDecoderChanged(isHardDecoder: Boolean) {
                    VideoPlayerSPUtil.instance.isEnableHardDecoder = isHardDecoder
                    startPosition = getCurrentPosition()
                    // 停止播放视频
                    mIMixPlayer?.stop()
                    // 切换编码方式
                    mIMixPlayer?.setEnableHardDecoder(isHardDecoder)
                    // 重启播放
                    onVodInit(videoUrl!!, mControlView.getTitle(), startPosition, headerMap)
                }

                override fun onPlayerChanged(type: Int) {
                    if (mIMixPlayer?.getPlayerType() == type) return
                    startPosition = getCurrentPosition()
                    val speedValue = mIMixPlayer?.getSpeed()?:1f
                    mIMixPlayer?.onVodRelease()
                    removeViewAt(0)
                    // 初始化播放器
                    initMixPlayer(playerType = type)
                    // 重启播放
                    clearDelayHide()
                    // 判断4g和网络
                    if (!isPlayDownloadVideo) {
                        val isError = mErrorStatusView.onVodInit()
                        if (isError) {
                            mLoadingView.hide()
                            return
                        }
                    }
                    // 播放器设置到初始状态
                    mIMixPlayer?.onVodInit(videoUrl, startPosition, headerMap, isPlayDownloadVideo, mediaSourceFactory)
                    mLoadingView.onVodInit(mIMixPlayer?.getPlayerType())
                    mIMixPlayer?.setSpeed(speedValue)

                    dialogHandler?.sendEmptyMessage(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
                }

                override fun onHideDialog() {
                    dialogHandler?.sendEmptyMessage(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)

                }
            })

            // 触摸moreView的时候不隐藏
            showMoreView.setOnTouchDownListener(object : ShowMoreView.OnTouchDownListener {
                override fun onTouchDown() {
                    dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
                }

                override fun onTouchUp() {
                    // 延迟隐藏
                    delayHideMoreDialog()
                }
            })
            showMoreView.setBrightness(mScreenBrightness)
            // 亮度seek
            showMoreView.setOnLightSeekChangeListener { _, progress, _ ->
                setWindowBrightness(progress)
                mScreenBrightness = progress
            }
            showMoreView.setOnShowMoreViewDisplayListener(object : ShowMoreView.OnShowMoreViewDisplayListener {
                override fun onCancelDelayHide() {
                    dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
                }

                override fun onStartDelayHide() {
                    // 延迟隐藏
                    delayHideMoreDialog()
                }
            })
        }
        val moreValue = AliyunShowMoreValue()
        moreValue.screenBrightness = mScreenBrightness
        moreValue.speed = mIMixPlayer?.getSpeed()?:1f
        moreValue.isLoop = mIMixPlayer?.getLoop()?:false
        moreValue.scaleMode = mControlView.getScaleMode()
        moreValue.currentPlayerType = mIMixPlayer?.getPlayerType()?:PlayerType.MEDIA3
        moreValue.userSpecifiedPlayerType = playerType
        moreValue.isHideOtherPlayers = isHideOtherPlayers
        moreValue.isDownloadVideo = isPlayDownloadVideo
        moreValue.playerModel = videoPlayModel
        val showMoreView = showMoreDialog?.contentView as ShowMoreView?
        showMoreView?.configViews(moreValue)
        showMoreDialog?.show()
        // 延迟隐藏
        delayHideMoreDialog()
    }


    /**
     * 清空播放器信息
     */
    private fun clearData() {
        videoUrl = null
        headerMap = null
        startPosition = 0
    }


    private fun getMixPlayer(): View? {
        // 初始尺寸调整
        var playerView: View? = null
        val childCount = childCount
        for (index in 0 until childCount) {
            val child = getChildAt(index)
            if (child is IMixPlayer) {
                playerView = child
                break
            }
        }
        return playerView
    }

    private fun scaleVideoFit(playerViewLayoutParams: LayoutParams){
        playerViewLayoutParams.width = 0
        playerViewLayoutParams.height = 0
        playerViewLayoutParams.dimensionRatio = currentPlayerRadio
        playerViewLayoutParams.startToStart = LayoutParams.PARENT_ID
        playerViewLayoutParams.endToEnd = LayoutParams.PARENT_ID
        playerViewLayoutParams.topToTop = LayoutParams.PARENT_ID
        playerViewLayoutParams.bottomToBottom = LayoutParams.PARENT_ID
    }

    private fun scaleVideo169(playerViewLayoutParams: LayoutParams){
        playerViewLayoutParams.width = 0
        playerViewLayoutParams.height = 0
        playerViewLayoutParams.dimensionRatio = "16:9"

        playerViewLayoutParams.startToStart = LayoutParams.PARENT_ID
        playerViewLayoutParams.endToEnd = LayoutParams.PARENT_ID
        playerViewLayoutParams.topToTop = LayoutParams.PARENT_ID
        playerViewLayoutParams.bottomToBottom = LayoutParams.PARENT_ID
    }

    private fun scaleVideo43(playerViewLayoutParams: LayoutParams){
        playerViewLayoutParams.width = 0
        playerViewLayoutParams.height = 0
        playerViewLayoutParams.dimensionRatio = "4:3"

        playerViewLayoutParams.startToStart = LayoutParams.PARENT_ID
        playerViewLayoutParams.endToEnd = LayoutParams.PARENT_ID
        playerViewLayoutParams.topToTop = LayoutParams.PARENT_ID
        playerViewLayoutParams.bottomToBottom = LayoutParams.PARENT_ID
    }

    private fun scaleVideoFull(playerViewLayoutParams: LayoutParams){
        playerViewLayoutParams.width = LayoutParams.MATCH_PARENT
        playerViewLayoutParams.height = LayoutParams.MATCH_PARENT
        playerViewLayoutParams.dimensionRatio = null

        playerViewLayoutParams.startToStart = LayoutParams.PARENT_ID
        playerViewLayoutParams.topToTop = LayoutParams.PARENT_ID
        playerViewLayoutParams.bottomToBottom = LayoutParams.UNSET
    }

    /**
     * 设置缩放模式
     *
     * @param scaleMode 缩放模式
     */
    private fun setScaleMode(scaleMode: Int) {
        // 视频大小获取失效
        if (videoOriginWidth <= 0 || videoOriginHeight <= 0) {
            Log.e("Mix播放器", "视频尺寸获取失败，width or height <= 0")
            return
        }
        Log.e("视频尺寸调整", "当前源视频比例 -> $currentPlayerRadio, 目标比例：$scaleMode")
        // 获取播放器
        val playerView = getMixPlayer()
        if (playerView == null) return
        if (BuildConfig.DEBUG) {
            val mode = when (scaleMode) {
                Constants.VIDEO_RESIZE_FIT -> "自适应"
                Constants.VIDEO_RESIZE_169 -> "16:9"
                Constants.VIDEO_RESIZE_43 -> "4:3"
                else -> "平铺"
            }
            Log.e("视频尺寸调整", "需要调整播放器比例 -> $mode")
        }
        // 初始 FullParent, TopToTop, StartToStart
        val playerViewLayoutParams = playerView.layoutParams as LayoutParams
        when(scaleMode){
            Constants.VIDEO_RESIZE_FIT -> {
                scaleVideoFit(playerViewLayoutParams)
            }
            Constants.VIDEO_RESIZE_169 -> {
                scaleVideo169(playerViewLayoutParams)
            }

            Constants.VIDEO_RESIZE_43 -> {
                scaleVideo43(playerViewLayoutParams)
            }
            else -> {
                scaleVideoFull(playerViewLayoutParams)
            }
        }


        playerView.layoutParams = playerViewLayoutParams



        // 获取播放的布局信息
//        val playerLayoutParams = playerView.layoutParams as LayoutParams
//        playerLayoutParams.startToStart = LayoutParams.PARENT_ID
//        playerLayoutParams.endToEnd = LayoutParams.PARENT_ID
//        playerLayoutParams.topToTop = LayoutParams.PARENT_ID
//        playerLayoutParams.bottomToBottom = LayoutParams.PARENT_ID
//        // 当前视频的宽高比
//        val videoRadio = videoOriginWidth * 1f / videoOriginHeight
//        // 根据设置的缩放模式，进行缩放
//        when (scaleMode) {
//            Constants.VIDEO_RESIZE_FIT -> { //
//                val screenRadio = if (this.width == 0 || this.height == 0) {
//                    16f/9
//                } else {
//                    this.width * 1f / this.height
//                }
//                if (videoRadio > screenRadio) { // 以宽为边界
//                    playerLayoutParams.width = LayoutParams.MATCH_PARENT
//                    playerLayoutParams.height = 0
//                } else { // 以高为边界
//                    playerLayoutParams.width = 0
//                    playerLayoutParams.height = LayoutParams.MATCH_PARENT
//                }
//                playerLayoutParams.dimensionRatio = "$videoOriginWidth:$videoOriginHeight"
//            }
//            Constants.VIDEO_RESIZE_169 -> {
//                if (videoRadio > 16f/9) { // 以宽为边界
//                    playerLayoutParams.width = 0
//                    playerLayoutParams.height = LayoutParams.MATCH_PARENT
//                } else { // 以高为边界
//                    playerLayoutParams.width = LayoutParams.MATCH_PARENT
//                    playerLayoutParams.height = 0
//                }
//                playerLayoutParams.dimensionRatio = "16:9"
//
//            }
//            Constants.VIDEO_RESIZE_43 -> {
//                if (videoRadio > 4f/3) { // 以宽为边界
//                    playerLayoutParams.width = 0
//                    playerLayoutParams.height = LayoutParams.MATCH_PARENT
//                } else { // 以高为边界
//                    playerLayoutParams.width = LayoutParams.MATCH_PARENT
//                    playerLayoutParams.height = 0
//                }
//                playerLayoutParams.dimensionRatio = "4:3"
//            }
//            else -> {
//                playerLayoutParams.width = LayoutParams.MATCH_PARENT
//                playerLayoutParams.height = LayoutParams.MATCH_PARENT
//                playerLayoutParams.dimensionRatio = null
//            }
//        }
//        playerView.layoutParams = playerLayoutParams
        mControlView.setRadio(scaleMode)
    }

    // 延迟隐藏更多按钮
    private fun delayHideMoreDialog() {
        dialogHandler?.removeMessages(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG)
        dialogHandler?.sendEmptyMessageDelayed(DialogHandler.MSG_WHAT_HIDE_MORE_DIALOG, delayHideControlTime)
    }

    class DialogHandler(private val mixPlayerView: MixPlayerView): Handler(Looper.getMainLooper()){
        companion object {
            val MSG_WHAT_HIDE_CONTROL_VIEW = 0
            val MSG_WHAT_HIDE_MORE_DIALOG = 1
        }
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                MSG_WHAT_HIDE_CONTROL_VIEW -> mixPlayerView.onVodSwitchDisplayControlView()

                MSG_WHAT_HIDE_MORE_DIALOG -> mixPlayerView.hideMoreDialog()
            }
        }
    }



}